package com.muyu.danmo.service.impl;

import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.core.utils.StringUtils;
import com.muyu.common.core.web.domain.BaseEntity;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.danmo.domain.*;
import com.muyu.danmo.mapper.*;
import com.muyu.danmo.service.IDanmoCommunityService;
import com.muyu.danmo.service.IDanmoUserFollowsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 社区信息Service业务处理层
 *
 * @author : kunzong
 * @date : 2024-11-19
 */
@Service
public class DanmoCommunityServiceImpl implements IDanmoCommunityService {

    @Autowired
    private DanmoCommunityMapper danmoCommunityMapper;

    @Autowired
    private DanmoInformationServiceImpl danmoInformationServicel;

    @Autowired
    private DanmoCommunityPictureMapper danmoCommunityPictureMapper;

    @Autowired
    private DanmoCommunityCommentMapper danmoCommunityCommentMapper;

    @Autowired
    private DanmoCommunityLikeMapper danmoCommunityLikeMapper;

    @Autowired
    private DanmoCommunityFavoriteMapper danmoCommunityFavoriteMapper;

    @Autowired
    private DanmoUserFollowsMapper danmoUserFollowsMapper;

    @Autowired
    private IDanmoUserFollowsService danmoUserFollowsService;


    @Override
    public List<DanmoCommunity> selectDanmoCommunityList(DanmoCommunity danmoCommunity) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        System.out.println(danmoCommunity.getStartTime());
        System.out.println(danmoCommunity.getEndTime());

        List<DanmoCommunity> danmoCommunities = danmoCommunityMapper.selectDanmoCommunityList(danmoCommunity);
        //        获取帖子的点赞数，评论数和收藏数
        for (DanmoCommunity community : danmoCommunities) {
            communityAdd(community);
        }
        timeDifference(danmoCommunities);
        return danmoCommunities;
    }

    /**
     * 帖子点赞数，评论数，收藏数，是否关注
     *
     * @param community
     */
    private void communityAdd(DanmoCommunity community) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null) {
            //        查询该用户是否被关注
            DanmoUserFollows danmoUserFollows = new DanmoUserFollows();
            danmoUserFollows.setFollowerId(loginUser.getUserid());
            danmoUserFollows.setFolloweeId(community.getAuthorId());
            List<DanmoUserFollows> danmoUserFollowsList = danmoUserFollowsMapper.selectDanmoUserFollowsfanList(danmoUserFollows);
            if (danmoUserFollowsList.size() != 0) {
                community.setFollowThisUser(danmoUserFollowsList.get(0).getStatus());
            }
        }

//        设置点赞数，评论数，收藏数
        if (community.getDanmoCommunityLikeList() != null) {
            community.setLikes((long) community.getDanmoCommunityLikeList().size());
        } else {
            community.setLikes(0L);
        }
        if (community.getDanmoCommunityCommentList() != null) {
            community.setComments((long) community.getDanmoCommunityCommentList().size());
        } else {
            community.setComments(0L);
        }
        if (community.getDanmoCommunityFavoriteList() != null) {
            community.setCollects((long) community.getDanmoCommunityFavoriteList().size());
        } else {
            community.setCollects(0L);
        }

//        判断是否点赞和收藏
        //        用户id
        Long userId = 0L;
        if (loginUser != null) {
            userId = loginUser.getUserid();
        }
        if(community.getAuthorId().equals(userId)){
            community.setIsMine("true");
        }else {
            community.setIsMine("false");
        }
        if (userId != 0L) {
            if (community.getDanmoCommunityLikeList() != null) {
                for (DanmoCommunityLike danmoCommunityLike : community.getDanmoCommunityLikeList()) {
                    if (danmoCommunityLike.getUserId().equals(userId)) {
                        community.setLikeName("true");
                    }
                }
            }
            if (community.getDanmoCommunityFavoriteList() != null) {
                for (DanmoCommunityFavorite danmoCommunityFavorite : community.getDanmoCommunityFavoriteList()) {
                    if (danmoCommunityFavorite.getUserId().equals(userId)) {
                        community.setFavoriteName("true");
                    }
                }
            }
        }
    }

    @Override
    public DanmoCommunity selectDanmoCommunityById(Long id) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = 0L;
        if (loginUser != null) {
            userId = loginUser.getUserid();
        }
        DanmoCommunity danmoCommunity = danmoCommunityMapper.selectDanmoCommunityByIdAndUserId(id, userId);
        if (danmoCommunity == null) {
            return null;
        }
        if (danmoCommunity.getViews() == null) {
            danmoCommunity.setViews(0L);
        }
        danmoCommunity.setViews(danmoCommunity.getViews() + 1);
        communityAdd(danmoCommunity);
        List<DanmoCommunity> danmoCommunities = new ArrayList<>();
        danmoCommunities.add(danmoCommunity);
        timeDifference(danmoCommunities);
        List<DanmoCommunityComment> danmoCommunityComments = danmoCommunities.get(0).getDanmoCommunityCommentList();
        timeDifference(danmoCommunityComments);
        danmoCommunityCommentsAdd(danmoCommunityComments);
        danmoCommunityMapper.updateDanmoCommunity(danmoCommunity);
        return danmoCommunities.get(0);
    }


    /**
     * 评论点赞数，是否点赞
     *
     * @param danmoCommunityComments
     */
    private void danmoCommunityCommentsAdd(List<DanmoCommunityComment> danmoCommunityComments) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null) {
//            //        查询该用户是否点赞该评论
//            DanmoCommunityCommentLike danmoCommunityCommentLike = new DanmoCommunityCommentLike();
//            danmoCommunityCommentLike.setUserId(loginUser.getUserid());
//            danmoCommunityCommentLike.setPostId(community.getAuthorId());
//            List<DanmoUserFollows> danmoUserFollowsList = danmoUserFollowsMapper.selectDanmoUserFollowsfanList(danmoUserFollows);
//            if (danmoUserFollowsList.size() != 0) {
//                community.setFollowThisUser(danmoUserFollowsList.get(0).getStatus());
//            }
        }
    }

    @Override
    public Result insertDanmoCommunity(DanmoCommunity danmoCommunity) {
        Result judgment = judgment(danmoCommunity);
        if (judgment != null) {
            return judgment;
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return Result.notLoggedIn("请登录");
        }
        danmoCommunity.setAuthorId(loginUser.getUserid());

/*        DanmoInformation danmoInformation = danmoInformationServicel.selectUserID(loginUser.getUserid());
        if (danmoInformation == null) {
            return Result.error("请先完善个人信息");
        }*/
        danmoCommunity.setCreateBy(String.valueOf(loginUser.getUserid()));
        danmoCommunity.setCreateTime(DateUtils.getNowDate());
        System.out.println(DateUtils.getNowDate());
        danmoCommunity.setUpdateBy(String.valueOf(loginUser.getUserid()));
        danmoCommunity.setUpdateTime(DateUtils.getNowDate());
        danmoCommunity.setViews(0L);
        int rows = danmoCommunityMapper.insertDanmoCommunity(danmoCommunity);
        List<DanmoCommunityPicture> danmoCommunityPictureList = danmoCommunity.getDanmoCommunityPictureList();
        Long id = danmoCommunity.getId();
        danmoCommunityPictureAdd(id, danmoCommunityPictureList);
        return rows > 0 ? Result.success(rows, "新增成功") : Result.error("新增失败");
    }

    @Override
    public Result updateDanmoCommunity(DanmoCommunity danmoCommunity) {
        Result judgment = judgment(danmoCommunity);
        if (judgment != null) {
            return judgment;
        }
        danmoCommunity.setUpdateTime(DateUtils.getNowDate());
        Long id = danmoCommunity.getId();
//        先删除旧的图片
        danmoCommunityPictureDelete(id);
//        再添加新的图片
        danmoCommunityPictureAdd(id, danmoCommunity.getDanmoCommunityPictureList());
        int rows = danmoCommunityMapper.updateDanmoCommunity(danmoCommunity);
        return rows > 0 ? Result.success(rows, "修改成功") : Result.error("修改失败");
    }


    /**
     * 删除社区表信息
     *
     * @param ids 社区表ID数组
     */
    @Override
    public void deleteDanmoCommunityByIds(Long[] ids) {
        List<DanmoCommunity> danmoCommunities = danmoCommunityMapper.selectDanmoCommunityByIds(ids);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        for (DanmoCommunity danmoCommunity : danmoCommunities) {
            Long userid = loginUser.getUserid();
            if (!danmoCommunity.getCreateBy().equals(userid)) {
                continue;
            }
        }
//        删除社区表
        danmoCommunityMapper.deleteDanmoCommunityByIds(ids);
//        循环其他信息
        for (Long id : ids) {
            danmoCommunityCommentDelete(id);
            danmoCommunityLikeDelete(id);
            danmoCommunityFavoriteDelete(id);
            danmoCommunityPictureDelete(id);
        }


    }

    /**
     * 查询关注列表
     *
     * @param danmoCommunity
     * @return
     */
    @Override
    public List<DanmoCommunity> selectDanmoCommunityAttentionList(DanmoCommunity danmoCommunity) {
//        先查询出该用户关注的所有用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        DanmoUserFollows danmoUserFollows = new DanmoUserFollows();
        danmoUserFollows.setFollowerId(loginUser.getUserid());
        List<DanmoUserFollows> list = danmoUserFollowsService.selectDanmoUserFollowsList(danmoUserFollows);
//        获取这些用户下的所有用户名
        List<Long> followeeIdList = list.stream().map(DanmoUserFollows::getFolloweeId).toList();
//        获取这些用户下的所有帖子
        List<DanmoCommunity> danmoCommunities = List.of();
        if (followeeIdList.size() == 0) {
            return danmoCommunities;
        }
         danmoCommunities = danmoCommunityMapper.selectDanmoCommunityFolloweeIdList(followeeIdList);
        if (danmoCommunities.size() == 0) {
            return danmoCommunities;
        }
        for (DanmoCommunity community : danmoCommunities) {
            communityAdd(community);
        }
        //        计算出时间差
        timeDifference(danmoCommunities);
        return danmoCommunities;
    }


    /**
     * 热门社区(排序)
     *
     * @param danmoCommunity
     * @return
     */
    @Override
    public List<DanmoCommunity> selectDanmoCommunityPopularList(DanmoCommunity danmoCommunity) {
        List<DanmoCommunity> danmoCommunities = danmoCommunityMapper.selectDanmoCommunityPopularList(danmoCommunity);
        for (DanmoCommunity community : danmoCommunities) {
            communityAdd(community);
        }
        timeDifference(danmoCommunities);
        return danmoCommunities;
    }

    /**
     * 隐藏帖子
     *
     * @param ids
     * @return
     */
    @Override
    public Result hidePostsDanmoCommunityByIds(Long[] ids) {
        List<DanmoCommunity> danmoCommunitys = danmoCommunityMapper.selectDanmoCommunityByIds(ids);
        for (DanmoCommunity danmoCommunity : danmoCommunitys) {
            if (danmoCommunity != null) {
                if (danmoCommunity.getWhetherToHide() == null) {
                    danmoCommunity.setWhetherToHide("已隐藏");
                    danmoCommunity.setUpdateTime(DateUtils.getNowDate());
                    danmoCommunityMapper.updateDanmoCommunity(danmoCommunity);
                }
            }
        }
        return Result.success(1, "隐藏成功");
    }

    /**
     * 取消隐藏帖子
     *
     * @param ids
     * @return
     */
    @Override
    public Result cancelHidePostsDanmoCommunityByIds(Long[] ids) {
        List<DanmoCommunity> danmoCommunitys = danmoCommunityMapper.selectDanmoCommunityByIds(ids);
        for (DanmoCommunity danmoCommunity : danmoCommunitys) {
            if (danmoCommunity != null) {
                if (danmoCommunity.getWhetherToHide() == null) {
                    return Result.success(1, "该帖子已展示");
                }
                if (danmoCommunity.getWhetherToHide().equals("已隐藏")) {
                    danmoCommunity.setWhetherToHide(null);
                    danmoCommunity.setUpdateTime(DateUtils.getNowDate());
                    danmoCommunityMapper.updateDanmoCommunity(danmoCommunity);
                }
            }
        }
        return Result.success(1, "取消隐藏成功");
    }

    /**
     * 其他用户的收藏
     *
     * @param danmoCommunity
     * @return
     */
    @Override
    public List<DanmoCommunity> selectOtherCollectionDanmoCommunityList(DanmoCommunity danmoCommunity) {
        List<DanmoCommunity> danmoCommunityList = new ArrayList<>();
//        先查询出该用户的所有收藏（主要是看收藏的帖子ID）
        List<Long> ids = new ArrayList<>();
        List<DanmoCommunityFavorite> danmoCommunityFavoriteList = danmoCommunityFavoriteMapper.selectDanmoCommunityFavoriteByUserId(danmoCommunity.getAuthorId());
        if (danmoCommunityFavoriteList.size() == 0) {
            return danmoCommunityList;
        } else {
            for (DanmoCommunityFavorite danmoCommunityFavorite : danmoCommunityFavoriteList) {
                Long postId = danmoCommunityFavorite.getPostId();
                ids.add(postId);
            }
            List<DanmoCommunity> danmoCommunities = danmoCommunityMapper.selectDanmoCommunityByIdss(ids);
            for (DanmoCommunity community : danmoCommunities) {
                communityAdd(community);
            }
            timeDifference(danmoCommunities);
            return danmoCommunities;
        }
       /* List<DanmoCommunity> danmoCommunities = danmoCommunityMapper.selectOtherCollectionDanmoCommunityList(danmoCommunity);
//        danmoCommunityList是要发给前端的具体数据
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = 0L;
        if (loginUser != null) {
            userId = loginUser.getUserid();
        }

        //        获取帖子的点赞数，评论数和收藏数
        for (DanmoCommunity community : danmoCommunities) {
            communityAdd(community);
            if (community.getDanmoCommunityFavoriteList() != null) {
                for (DanmoCommunityFavorite danmoCommunityFavorite : community.getDanmoCommunityFavoriteList()) {
                    if (danmoCommunityFavorite.getUserId().equals(danmoCommunity.getAuthorId())) {
                        danmoCommunityList.add(community);
                    }
                }
            }
        }
        for (DanmoCommunity community : danmoCommunityList) {
            if (community.getDanmoCommunityFavoriteList() != null) {
                for (DanmoCommunityFavorite danmoCommunityFavorite : community.getDanmoCommunityFavoriteList()) {
                    if (userId != 0L) {
                        if (danmoCommunityFavorite.getUserId().equals(userId)) {
                            community.setFavoriteName("true");
                        } else {
                            community.setFavoriteName(null);
                        }
                    } else {
                        community.setFavoriteName(null);
                    }
                }
            }
        }


        timeDifference(danmoCommunities);
//        if (danmoCommunities != null) {
//            for (DanmoCommunity community : danmoCommunities) {
//                if (community.getFavoriteName() != null) {
//                    for (DanmoCommunityFavorite danmoCommunityFavorite : community.getDanmoCommunityFavoriteList()) {
//                        if (danmoCommunityFavorite.getUserId().equals(danmoCommunity.getAuthorId())) {
//                            community.setFavoriteName("true");
//                        }
//                    }
//                }
//            }
//        }
        return danmoCommunityList;*/
    }

    @Override
    public List<DanmoCommunity> selectDanmoCommunityMyCommunityList(DanmoCommunity danmoCommunity) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        List<DanmoCommunity> danmoCommunities = danmoCommunityMapper.selectDanmoCommunityMyCommunityList(danmoCommunity);
        //        获取帖子的点赞数，评论数和收藏数
        for (DanmoCommunity community : danmoCommunities) {
            communityAdd(community);

        }
        timeDifference(danmoCommunities);
        return danmoCommunities;
    }


    @Override
    public List<DanmoCommunity> selectDanmoCommunityLists(DanmoCommunity danmoCommunity) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        System.out.println(danmoCommunity.getStartTime());
        System.out.println(danmoCommunity.getEndTime());
        List<DanmoCommunity> danmoCommunities = danmoCommunityMapper.selectDanmoCommunityLists(danmoCommunity);
        //        获取帖子的点赞数，评论数和收藏数
        for (DanmoCommunity community : danmoCommunities) {
            communityAdd(community);
        }
        timeDifference(danmoCommunities);
        return danmoCommunities;
    }

    /**
     * 时间差
     *
     * @param entities
     */
    public static <T extends BaseEntity> void timeDifference(List<T> entities) {
        LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
        for (T entity : entities) {
            Date updateTime = entity.getUpdateTime();
            LocalDateTime updateDateTime = updateTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            Duration duration = Duration.between(updateDateTime, now);

            long minutes = duration.toMinutes();
            long hours = duration.toHours();
            long days = duration.toDays();
            if (minutes < 1) {
                entity.setTimeAgo("刚刚");
            } else if (minutes < 60) {
                entity.setTimeAgo(minutes + " 分钟前");
            } else if (hours < 24) {
                entity.setTimeAgo(hours + " 小时前");
                System.out.println("Time difference: " + hours + " hours");
            } else if (days < 30) {
                entity.setTimeAgo(days + "天前");
                System.out.println("Time difference: " + days + " days");
            } else if (days < 365) {
                long months = days / 30;
                entity.setTimeAgo(months + "个月前");
                System.out.println("Time difference: " + months + " months");
            } else {
                long years = days / 365;
                entity.setTimeAgo(years + "年前");
                System.out.println("Time difference: " + years + " years");
            }
        }
    }


    /**
     * 判断是否为空
     *
     * @param danmoCommunity 社区对象
     * @return
     */
    private Result judgment(DanmoCommunity danmoCommunity) {
        if (danmoCommunity.getContent() == null || danmoCommunity.getContent().equals("")) {
            return Result.error("请输入帖子内容");
        }
        return null;
    }

    /**
     * 添加图片
     */
    private void danmoCommunityPictureAdd(Long id, List<DanmoCommunityPicture> danmoCommunityPictureList) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser)) {
            List<DanmoCommunityPicture> list = new ArrayList<>();
            for (DanmoCommunityPicture danmoCommunityPicture : danmoCommunityPictureList) {
                // 检查图片是否不为 null 且不为空字符串
                if (danmoCommunityPicture.getPicture() != null && !danmoCommunityPicture.getPicture().trim().isEmpty()) {
                    danmoCommunityPicture.setCreateBy(String.valueOf(loginUser.getUserid()));
                    danmoCommunityPicture.setCreateTime(DateUtils.getNowDate());
                    danmoCommunityPicture.setUpdateBy(String.valueOf(loginUser.getUserid()));
                    danmoCommunityPicture.setUpdateTime(DateUtils.getNowDate());
                    danmoCommunityPicture.setProductId(id);
                    list.add(danmoCommunityPicture);
                }
            }
            if (list.size() > 0) {
                danmoCommunityPictureMapper.insertBatch(list);
            }
        }
    }

    /**
     * 删除图片
     */
    private void danmoCommunityPictureDelete(Long id) {
        danmoCommunityPictureMapper.deleteByCommunity(id);
    }

    /**
     * 删除评论
     */
    private void danmoCommunityCommentDelete(Long id) {
        danmoCommunityCommentMapper.deleteByCommunity(id);
    }

    /**
     * 删除点赞
     *
     * @param id
     */
    private void danmoCommunityLikeDelete(Long id) {
        danmoCommunityLikeMapper.deleteByCommunity(id);
    }

    /**
     * 删除收藏
     *
     * @param id
     */
    private void danmoCommunityFavoriteDelete(Long id) {
        danmoCommunityFavoriteMapper.deleteByCommunity(id);
    }
}
